import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { useEditor, EditorContent } from '@tiptap/react';
import { Button } from "antd";
import StarterKit from '@tiptap/starter-kit';
import TextStyle from "@tiptap/extension-text-style";
import { Extension, Node } from '@tiptap/core';
import Focus from '@tiptap/extension-focus';
import Spannode from './Spannode';

const Tiptap = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    getHtml: getHtml,
  }))

  const CustomSpannode = Spannode.extend({
    parseHTML() {
      return [
        { tag: `span[data-type="${this.name}"]` },
      ]
    },
  })

  const editor = useEditor({
    content: props.content,
    extensions: [
      StarterKit,
      Focus.configure({
        className: 'has-focus',
        mode: 'shallowest',
      }),
      CustomSpannode.configure({
        HTMLAttributes: {
          class: 'editor-input',
        },
      }),
      TextStyle,
    ],
    editorProps: {
      attributes: {
        class: 'ProseMirror-editor',
      },
      transformPastedText(text) {
        return text.toUpperCase()
      }
    },
    autofocus: true,
    editable: true,
    injectCSS: false,
  })

  const getHtml = () => {
    if (editor) {
      let content = editor.getHTML();
      return content;
    }
  }

  const AddChange = () => {
    editor.commands.insertContent(`<span data-type="spannode">&nbsp;${formatMessage({ id: 'personalizedInstructionLibrary.enterContent' })}</span><span>&nbsp;</span>`)
  }

  return (
    <>
      <EditorContent editor={editor} />
      <Button onClick={AddChange} style={{marginTop:10}}>{formatMessage({ id: 'personalizedInstructionLibrary.addPromptTextBox' })}</Button>
    </>
  )
})

export default Tiptap